package vikaa.ui;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vikaa.pullview.PullToRefreshImgListView;
import com.vikaa.pullview.PullToRefreshImgListView.OnRefreshListener;

import vikaa.adapter.AdapterTimelineForLookAround;
import vikaa.timelinepackage.AsyLoadImg;
import vikaa.timelinepackage.PinnedHeaderListView;
import vikaa.timelinepackage.TimelineComment;
import vikaa.timelinepackage.Timeline_item;
import vikaa.tools.BitmapManager;
import vikaa.tools.HttpUtil;
import vikaa.tools.StringUtils;
import vikaa.ui.Mywowo;
import vikaa.ui.WowoMember;
import vikaa.wowo.R;
import vikaa.wowo.cache.SpaceListSqlStoragePrivate;
import vikaa.wowo.cache.TwitterSqlStoragePrivate;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class TimelineForLookAround extends Activity implements OnItemClickListener,  OnGestureListener , OnDoubleTapListener{
	private ArrayList<Timeline_item> tlitem = new ArrayList<Timeline_item>();
	private ArrayList<Timeline_item> itemlist = new ArrayList<Timeline_item>() ;
	private AdapterTimelineForLookAround adapter;
	public static PinnedHeaderListView listView;
	public static PullToRefreshImgListView listview2;
	public static int page;
	public static String space_id;
	public static TimelineForLookAround tl;
	public static int count;
    //private View topview;
    public static String memberNum;
    private String credits;
    public static String space_name;
    public static String managerCount;
    private ImageView settingsBtn;
    private ImageView spacelistBtn;
    private ImageView addBtn;
    private RelativeLayout tipRl;
    private ImageView joinBtn;
    private RelativeLayout bottomImg;
    private TextView titleTv;
    private String coverUrl;
    private String role;
    private ImageView img;
    private BitmapManager bitmapManager;
    private TextView myContributionMsg;
    private TextView myContributionNumber;
    private TextView myContributionMsg2;
    private TextView memberNumTv;
    private RelativeLayout conRl;
    private LinearLayout ll;
    private String state;
    
    public static boolean isrefresh = false;
    public static boolean isfinish = false;
    public static boolean changedata = false;
    private boolean singleclick = false;
    private boolean doubleclick = false;
    private boolean fling = false;
    
    private GestureDetector mGestureDetector;  
    private int verticalMinDistance = 200;  
    private int minVelocity         = 0;  
    
    public static  View footerview;
    public static RelativeLayout foot;
    private RelativeLayout lookaroundBtn;
    
    
	@Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.timeline);
        role = getIntent().getExtras().getString("role");
        space_id = getIntent().getExtras().getString("sid");
        count = Integer.valueOf(getIntent().getExtras().getString("count"));
        space_name = getIntent().getExtras().getString("spacename");
        coverUrl = getIntent().getExtras().getString("cover");
        credits = SpaceListSqlStoragePrivate.getCredits(space_id, getIntent().getExtras().getString("uid"), TimelineForLookAround.this);
        memberNum = getIntent().getExtras().getString("member");
        managerCount = getIntent().getExtras().getString("host");
        state = getIntent().getExtras().getString("state");
        tl = this;
        isrefresh = false;
        isfinish = false;
        initdata();
        
        /*if(this.getWindowManager().getDefaultDisplay().getWidth() > ValueClass.LOW_DPI_WIDTH){
        	initlistview();
        }else{*/
        	initlistview2();
        	initview();
        //}
        //DialogService.showProgressDialog(Timeline.this, getString(R.string.get_timeline));
        //this.bitmapManager = new BitmapManager(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.bg_timeline_toppic_display));
        mGestureDetector = new GestureDetector((OnGestureListener) this);
    }
	@Override
	protected void onDestroy() {
		super.onDestroy();
		System.gc();
	}
	@Override
	protected void onResume() {
		super.onResume();
		
		singleclick = false;
		doubleclick = false;
		
		titleTv.setText(space_name);
	}
	public void initview(){
		titleTv = (TextView)findViewById(R.id.titleTv);
		spacelistBtn = (ImageView)findViewById(R.id.spacelistBtn);
		spacelistBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				TwitterSqlStoragePrivate.dropmyTwitter(getApplicationContext());
				TwitterSqlStoragePrivate.dropfilelistTwitter(getApplicationContext());
			}
		});
		settingsBtn = (ImageView)findViewById(R.id.settingsBtn);
		settingsBtn.setVisibility(View.INVISIBLE);
		tipRl = (RelativeLayout)findViewById(R.id.tipRl);
		addBtn = (ImageView)findViewById(R.id.addBtn);
		joinBtn = (ImageView)findViewById(R.id.joinBtn);
		bottomImg = (RelativeLayout)findViewById(R.id.bottomImg);
		joinBtn.setVisibility(View.INVISIBLE);
		bottomImg.setVisibility(View.INVISIBLE);
		addBtn.setVisibility(View.INVISIBLE);
		tipRl.setVisibility(View.INVISIBLE);
		listview2.conRl.setVisibility(View.INVISIBLE);
		listview2.ll.setVisibility(View.INVISIBLE);
		
		lookaroundBtn = (RelativeLayout)findViewById(R.id.lookaoundBtn);
		lookaroundBtn.setVisibility(View.VISIBLE);
		lookaroundBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//header.setVisibility(View.VISIBLE);
				//DialogService.showProgressDialog(WowoRecommand.this, getString(R.string.get_wowo_list));
				setResult(RESULT_OK);
				finish();
			}
		});
	}
	public void initlistview2(){
		//footer
		footerview = getLayoutInflater().inflate(R.layout.timeline_loadmore, null);
		foot = (RelativeLayout)footerview.findViewById(R.id.footerview);
		View bottomview = getLayoutInflater().inflate(R.layout.timeline_botom, null);
		//foot.setVisibility(View.VISIBLE);
		//adapter
		adapter = new AdapterTimelineForLookAround(getLayoutInflater(),tlitem,TimelineForLookAround.this);
		adapter.ran = true;
		listview2 = (PullToRefreshImgListView) findViewById(R.id.section_list_view);
		if(!StringUtils.isEmpty(coverUrl)){
			AsyLoadImg.loadTimeBg(HttpUtil.HttpUrlComplete(coverUrl), listview2.coverImage);
		}else{
			listview2.coverImage.setBackgroundResource(R.drawable.bg_timeline_toppic_display);
		}
		listview2.addFooterView(footerview, null, false);
		listview2.addFooterView(bottomview);
		listview2.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if(mGestureDetector.onTouchEvent(event)){
					return false;
				}
				if(onSingleTapConfirmed(event)){
					return false;
				}			
				return false;
			}
		});
		listview2.setClickable(true);
		//listview2.setOnItemClickListener(this);
		listview2.setAdapter(adapter);
		listview2.setOnScrollListener(adapter);
		listview2.setOnRefreshListener(new OnRefreshListener() {
			public void onRefresh() {
				adapter.ran = true;
				listview2.onRefreshComplete();
			}
		});
	}
    public void initdata(){
    	page = 1;
    	new TimelineThread(String.valueOf(page), space_id, 1).start();
    }
    Handler mhandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				listview2.loadingAni.setVisibility(View.GONE);
				if(msg.obj != null){
					ArrayList<Timeline_item> strings = (ArrayList<Timeline_item>) msg.obj;
					if(!strings.isEmpty()){
						tlitem.addAll(strings);
						//TimeLineSqlStoragePrivate.saveTimeLine(strings, space_id, Timeline.this);
						//tlitem.addAll(TimeLineSqlStoragePrivate.getTimeLine(space_id, page, Timeline.this));
					}
					adapter.notifyDataSetChanged();
				}
				break;
			case 2:
				listview2.loadingAni.setVisibility(View.GONE);
				foot.setVisibility(View.INVISIBLE);
				adapter.ran = true;
				ArrayList<Timeline_item> strings = (ArrayList<Timeline_item>) msg.obj;
				if(!strings.isEmpty()){
					tlitem.addAll(strings);
					//TimeLineSqlStoragePrivate.saveTimeLine(strings, space_id, Timeline.this);
					//tlitem.addAll(TimeLineSqlStoragePrivate.getTimeLine(space_id, page, Timeline.this));
					adapter.notifyDataSetChanged();
				}
				break;
			case 3:
				listview2.loadingAni.setVisibility(View.GONE);
				if(msg.obj != null && ((String)msg.obj).equals("没有微博")){
					adapter.ran = false;
					listview2.removeFooterView(footerview);
					/*Toast toast = new Toast(TimelineForLookAround.this);
		        	toast = Toast.makeText(TimelineForLookAround.this, getString(R.string.load_full), 500);
		        	toast.setGravity(Gravity.CENTER, 0, 0);
		        	toast.show();*/
					//initlistview();
				}else if(msg.obj != null ){
					Toast.makeText(TimelineForLookAround.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
					//initlistview();
				}
				else
					Toast.makeText(TimelineForLookAround.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				listview2.loadingAni.setVisibility(View.GONE);
				adapter.ran = true;
				/*tlitem.addAll(TimeLineSqlStoragePrivate.getTimeLine(space_id, page, Timeline.this));
				if(page == 1)
					initlistview();
				else
					adapter.notifyDataSetChanged();*/
				Toast.makeText(TimelineForLookAround.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5:
				joinBtn.setVisibility(View.INVISIBLE);
				bottomImg.setVisibility(View.INVISIBLE);
				addBtn.setVisibility(View.VISIBLE);
				memberNumTv.setText(String.valueOf(Integer.valueOf(memberNum)+1));
				settingsBtn.setVisibility(View.VISIBLE);
				conRl.setVisibility(View.VISIBLE);
				ll.setVisibility(View.VISIBLE);
				Mywowo.isrefresh = true;
				break;
			case 6:
				listview2.loadingAni.setVisibility(View.GONE);
				if(msg.obj != null){
					Toast.makeText(TimelineForLookAround.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(TimelineForLookAround.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 7:
				listview2.loadingAni.setVisibility(View.GONE);
				ArrayList<Timeline_item> newlist = (ArrayList<Timeline_item>) msg.obj;
				//TimeLineSqlStoragePrivate.saveTimeLine(newlist, space_id, Timeline.this);
				tlitem.addAll(0, newlist);
				count += newlist.size();
				adapter.notifyDataSetChanged();
				break;
			case 8:
				//initlistview();
				break;
			}
			
		}
    };
    public class TimelineThread extends Thread{
    	private String page;
    	private String space_id;
    	private int m;
    	boolean isrun = true;
		public TimelineThread(String page, String space_id, int m) {
			super();
			this.page = page;
			this.space_id = space_id;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			itemlist.clear();
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("space_id", space_id);
    			map.put("page", page);
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/timeline", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray jsonArr = jsonObj.getJSONArray("info");
						for(int i=0;i<jsonArr.length();i++){
							Timeline_item item = new  Timeline_item();
							item.setAvatar(jsonArr.getJSONObject(i).getString("avatar"));
							item.setThumbnail_pic(jsonArr.getJSONObject(i).getString("thumbnail_pic"));
							item.setBmiddle_pic(jsonArr.getJSONObject(i).getString("bmiddle_pic"));
							item.setOriginal_pic(jsonArr.getJSONObject(i).getString("original_pic"));
							item.setCreate_at(jsonArr.getJSONObject(i).getString("created_at"));
							item.setIdstr(jsonArr.getJSONObject(i).getString("idstr"));
							item.setLike(jsonArr.getJSONObject(i).getString("like"));
							item.setNickname(StringEscapeUtils.unescapeHtml4(jsonArr.getJSONObject(i).getString("nickname")));
							item.setComments_count(jsonArr.getJSONObject(i).getString("comments_count"));
							item.setText(StringEscapeUtils.unescapeHtml4(jsonArr.getJSONObject(i).getString("text")));
							item.setHash(jsonArr.getJSONObject(i).getString("hash"));
							item.setIsLike(jsonArr.getJSONObject(i).getString("isLike"));
							itemlist.add(item);
						}
						Message msg = mhandler.obtainMessage(m);
						msg.obj = itemlist;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					Message msg = mhandler.obtainMessage(8);
					msg.sendToTarget();
					e.printStackTrace();
				}
    		}
    	}
    }
    class JoinThread extends Thread {
    	private boolean isrun = true;
    	@Override
    	public void run() {
    		while(isrun){
    			isrun = false;
    			try{
    				Map<String, String> map = new HashMap<String, String>();
    				map.put("space_id", space_id);
    				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL + "space/join", map));
    				if(jsonObj.getString("result").equals("1")){
    					Message msg = mhandler.obtainMessage(5);
						msg.sendToTarget();
    				}
    				else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(6);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
    			}catch(Exception e){
    				e.printStackTrace();
    			}
    		}
    	}
    }
    class TimelineNewThread extends Thread{
    	private String page;
    	private String space_id;
    	private int m;
    	boolean isrun = true;
		public TimelineNewThread(String page, String space_id, int m) {
			super();
			this.page = page;
			this.space_id = space_id;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			itemlist.clear();
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("space_id", space_id);
    			map.put("page", page);
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/timeline", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray jsonArr = jsonObj.getJSONArray("info");
						for(int i=0;i<jsonArr.length();i++){
							for(Timeline_item tl:tlitem){
								if(!tl.getHash().equals(jsonArr.getJSONObject(i).getString("hash"))){
									Timeline_item item = new  Timeline_item();
									item.setAvatar(jsonArr.getJSONObject(i).getString("avatar"));
									item.setThumbnail_pic(jsonArr.getJSONObject(i).getString("thumbnail_pic"));
									item.setBmiddle_pic(jsonArr.getJSONObject(i).getString("bmiddle_pic"));
									item.setOriginal_pic(jsonArr.getJSONObject(i).getString("original_pic"));
									item.setCreate_at(jsonArr.getJSONObject(i).getString("created_at"));
									item.setIdstr(jsonArr.getJSONObject(i).getString("idstr"));
									item.setLike(jsonArr.getJSONObject(i).getString("isLike"));
									item.setNickname(StringEscapeUtils.unescapeHtml4(jsonArr.getJSONObject(i).getString("nickname")));
									item.setComments_count(jsonArr.getJSONObject(i).getString("comments_count"));
									item.setText(StringEscapeUtils.unescapeHtml4(jsonArr.getJSONObject(i).getString("text")));
									item.setHash(jsonArr.getJSONObject(i).getString("hash"));
									itemlist.add(item);
								}
							}
						}
						Message msg = mhandler.obtainMessage(m);
						msg.obj = itemlist;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
    }
    class TwitterLikeThread extends Thread{
		private String url;
    	private String hash;
    	private int m;
    	boolean isrun = true;
		public TwitterLikeThread(String url, String hash, int m) {
			super();
			this.url = url;
			this.hash = hash;
			this.m = m;
		}
    	public void run() {
    		while(isrun){
    			isrun = false;
    			Map<String, String> map = new HashMap<String, String>();
    			map.put("hash", hash);
    			try {
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+url, map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(m);
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else {
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
    		}
    	}
	}
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		if(position != 0 && doubleclick){
			doubleclick = false;
			new TwitterLikeThread("twitter/like",tlitem.get(position-1).getHash(),8).start();
			tlitem.get(position-1).setLike("true");
		}
		if(position != 0 && singleclick && !fling){
			Intent i = new Intent(TimelineForLookAround.this,TimelineComment.class);
			i.putExtra("avater", tlitem.get(position-1).getAvatar());
			i.putExtra("nickname", tlitem.get(position-1).getNickname());
			i.putExtra("created_at", tlitem.get(position-1).getCreate_at());
			i.putExtra("bmiddle_pic", tlitem.get(position-1).getBmiddle_pic());
			i.putExtra("thumbnail_pic", tlitem.get(position-1).getThumbnail_pic());
			i.putExtra("text", tlitem.get(position-1).getText());
			i.putExtra("hash", tlitem.get(position-1).getHash());
			i.putExtra("comments_count", tlitem.get(position-1).getComments_count());
			i.putExtra("isLike", tlitem.get(position-1).getLike());
			i.putExtra("com", 0);
			startActivity(i);
		}
	}
	public boolean onDown(MotionEvent e) {
		return false;
	}
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(velocityX) > minVelocity) {  
	        finish() ;
	        fling = true;
	        return true;
	    }  
		return false;
	}
	public void onLongPress(MotionEvent e) {
		
	}
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}
	public void onShowPress(MotionEvent e) {
		
	}
	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}
	
	public boolean onDoubleTap(MotionEvent e) {
		singleclick = false;
		doubleclick = true;
		return true;
	}
	public boolean onDoubleTapEvent(MotionEvent e) {
		return true;
	}
	public boolean onSingleTapConfirmed(MotionEvent e) {
		singleclick = true;
		return false;
	}
}